package com.vavr.checkincms.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.text.CharSequenceUtil;
import com.vavr.checkincms.common.constant.CommonConstants;
import com.vavr.checkincms.common.domain.ResultEnum;
import com.vavr.checkincms.common.exception.BaseException;
import com.vavr.checkincms.constant.CheckinConstants;
import com.vavr.checkincms.domain.data.SystemUserInfoDO;
import com.vavr.checkincms.domain.dto.SystemUserInfoDTO;
import com.vavr.checkincms.mapper.SystemLoginMapper;
import com.vavr.checkincms.util.CheckinRequestUtils;
import lombok.Setter;
import org.springframework.web.servlet.HandlerExceptionResolver;

/**
 * CheckinSessionFilter
 *
 * @since 2.0.0
 */
public class CheckinSessionFilter implements Filter {
    @Setter
    private Set<String> whiteListUrl;

    @Setter
    private SystemLoginMapper systemLoginMapper;

    @Setter
    private HandlerExceptionResolver handlerExceptionResolver;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        whiteListUrl = Optional.ofNullable(filterConfig.getInitParameter(CheckinConstants.WHITE_LIST_URL))
                .map(t -> (Set<String>) new HashSet<>(Arrays.asList(t.split(";"))))
                .orElseGet(Collections::emptySet);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String servletPath = req.getServletPath();
        if (whiteListUrl.contains(servletPath) || CharSequenceUtil.equalsAny(servletPath, "/index.html", "/config.js",
                "/favicon.ico") || servletPath.startsWith("/assets") || servletPath.startsWith("/sso/login")) {
            chain.doFilter(request, response);
        }
        else {
            try {
                if (CheckinRequestUtils.getUserFromRequestAttributes().isEmpty()) {
                    Cookie[] cookies = req.getCookies();
                    if (cookies != null) {
                        Optional<SystemUserInfoDO> loginRecords = Arrays.stream(cookies)
                                .filter(v -> CommonConstants.CHECKIN_CMS_COOKIE_ID.equals(v.getName()))
                                .findAny()
                                .map(v -> systemLoginMapper.selectById(v.getValue()));
                        if (loginRecords.isPresent()) {
                            SystemUserInfoDO v = loginRecords.get();
                            CheckinRequestUtils.setUserToRequestAttributes(
                                    new SystemUserInfoDTO().setOperatorId(v.getOperatorId()));
                            chain.doFilter(request, response);
                        }
                    }
                    else {
                        throw new BaseException(ResultEnum.NOT_CHECKIN);
                    }
                }
                chain.doFilter(request, response);
            }
            catch (BaseException e) {
                handlerExceptionResolver.resolveException(req, resp, null, e);
            }
        }

    }
}
